package com.lujianfei.redpacketstat.ui

import android.app.AlertDialog
import android.content.DialogInterface
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.lujianfei.redpacketstat.Constant
import com.lujianfei.redpacketstat.R
import com.lujianfei.redpacketstat.base.BaseFragment
import com.lujianfei.redpacketstat.database.AppDatabase
import com.lujianfei.redpacketstat.databinding.FragmentMainBinding
import com.lujianfei.redpacketstat.ui.adapter.MainAdapter
import com.lujianfei.redpacketstat.ui.viewmodel.MainViewModel
import org.koin.android.ext.android.inject

class MainFragment : BaseFragment<FragmentMainBinding>() {

    companion object {
        private const val PARAM_STATUS = "status"
        fun newInstance(status: Int): MainFragment {
            val fragment = MainFragment()
            val bundle = Bundle()
            bundle.putInt(PARAM_STATUS, status)
            fragment.arguments = bundle
            return fragment
        }
    }

    private val mViewModel: MainViewModel by inject()
    private val adapter: MainAdapter = MainAdapter()

    override fun layoutId(): Int {
        return R.layout.fragment_main
    }

    override fun initView() {
        Log.d("VIEWMODEL==", " MainFragment mViewModel=$mViewModel")
        dataBinding?.recyclerView?.layoutManager = LinearLayoutManager(context)
        dataBinding?.recyclerView?.adapter = adapter
    }

    override fun initData() {
        adapter.mainViewModel = mViewModel
        mViewModel.loadData(arguments?.getInt(PARAM_STATUS)?: Constant.STATUS_UNPROCESSED).observe(this, androidx.lifecycle.Observer { userList ->
            userList?.let { userListAfterCheck ->
                mViewModel.appendAmount(userListAfterCheck) {
                    adapter.setData(userList)
                }
            }
        })
        mViewModel.uiState.observe(this, Observer { stateNonNull ->
            stateNonNull.showDialog?.let {
                showConfirmDialog(it.title, it.message) {
                    it.callback(true)
                }
            }
        })

        mViewModel.notifyTabUpdate()
    }


    private fun showConfirmDialog(title: String, message: String, callback: () -> Unit) {
        AlertDialog.Builder(context)
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton("确认") { _: DialogInterface, _: Int ->
                callback()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    fun notifyUpdate() {
        adapter.notifyItemRangeChanged(0, adapter.itemCount)
    }
}